<?php

namespace app\cms\controller;

use think\admin\Controller;
use think\admin\service\AdminService;
use think\admin\helper\QueryHelper;
use app\cms\model\StockGoods;
use app\cms\model\StockLogs;
use think\facade\Filesystem;

/**
 * 库存管理
 * @class Inventory
 * @package app\cms\controller
 */
class Inventory extends Controller
{
  /**
   * 库存管理
   * @auth true
   * @menu true
   * @throws \think\db\exception\DataNotFoundException
   * @throws \think\db\exception\DbException
   * @throws \think\db\exception\ModelNotFoundException
   */
  public function index()
  {
    $this->title = '库存管理';
    StockGoods::mQuery()->layTable(function () {}, static function (QueryHelper $query) {
      $query->where('deleted', 0);
      $query->dateBetween('create_at')->equal('type')->like('content,geoip,node');
    });
  }

  protected function _index_page_filter(array &$data)
  {
    foreach ($data as &$vo) {
      $vo['remaining'] = $vo['total'] - $vo['used'];
    }
  }
  /**
   * 新增
   * @auth true
   */
  public function add()
  {
    StockGoods::mForm('form');
  }

  /**
   * 编辑
   * @auth true
   */
  public function edit()
  {
    $this->_applyFormToken();
    StockGoods::mForm('form');
  }

  /**
   * 编辑入库
   * @auth true
   */
  public function inbound()
  {
    $this->goods_id = input('id', '');
    StockLogs::mForm('inbound');
    //$this->fetch();
  }
  
  protected function _inbound_form_filter(array &$data)
  {

    if (!$this->request->isGet()) {
      $data = $this->request->post();
      $goods = StockGoods::mk()->find($data['goods_id']);
      if ($goods->addStock($data['total_weight'], $this->app->session->get('user.nickname'), $data['note'], $data)) {
        $this->success('入库成功');
      }
      $this->error('入库失败：' . $goods->getError());
    }
  }

  /**
   * 编辑出库
   * @auth true
   */
  public function outbound()
  {
    $this->goods_id = input('id', '');
    StockLogs::mForm('outbound');
    //$this->fetch();
  }

  protected function _outbound_form_filter(array &$data)
  {

    if (!$this->request->isGet()) {
      $data = $this->request->post();
      $goods = StockGoods::mk()->find($data['goods_id']);
      $result = $goods->useStock($data['num'], $this->app->session->get('user.nickname'), $data['note'] ,$data);
      if ($result['status']) {
        $this->success($result['warning'] ?: '出库成功');
      }
      $this->error('出库失败：' . $result['error']);
    }
  }

  /**
   * 删除
   * @auth true
   */
  public function remove()
  {
    StockGoods::mDelete();
  }




  // 库存流水
  /**
   * 编辑库存流水
   * @auth true
   */
  public function logs()
  {
    $this->title = '库存流水';
    $this->goods_id = input('goods_id', '');
    StockLogs::mQuery()->layTable(function () {}, static function (QueryHelper $query) {


      $query->dateBetween('create_at')->order('create_at desc')->equal('goods_id,type');
    });
  }

  // 库存统计
  public function report()
  {
    $this->title = '库存统计';

    // 获取统计时间段
    $start = $this->request->get('start', date('Y-m-01'));
    $end = $this->request->get('end', date('Y-m-d'));

    // 统计入库总量
    $inTotal = $this->model->logs()
      ->where('type', 1)
      ->whereBetweenTime('create_time', $start, $end)
      ->sum('num');

    // 统计出库总量
    $outTotal = $this->model->logs()
      ->where('type', 0)
      ->whereBetweenTime('create_time', $start, $end)
      ->sum('num');

    // 统计商品库存
    $goods = $this->model->select();

    $this->assign([
      'start' => $start,
      'end' => $end,
      'inTotal' => $inTotal,
      'outTotal' => $outTotal,
      'goods' => $goods
    ]);

    $this->fetch();
  }

  // 批量导入
  public function import()
  {
    if ($this->request->isPost()) {
      $file = $this->request->file('file');
      if (!$file) {
        $this->error('请选择要导入的文件');
      }

      try {
        $data = Filesystem::read($file->getRealPath());
        $rows = array_map('str_getcsv', explode("\n", $data));

        $success = 0;
        $this->model->startTrans();
        foreach ($rows as $row) {
          if (count($row) < 3) continue;

          $goods = $this->model->where('name', $row[0])->find();
          if (!$goods) {
            $goods = $this->model->create([
              'name' => $row[0],
              'total' => $row[1],
              'used' => 0,
              'threshold' => $row[2]
            ]);
          } else {
            $goods->save([
              'total' => $goods->total + $row[1],
              'threshold' => $row[2]
            ]);
          }
          $success++;
        }
        $this->model->commit();
        $this->success("成功导入{$success}条记录");
      } catch (\Exception $e) {
        $this->model->rollback();
        $this->error('导入失败：' . $e->getMessage());
      }
    }
    $this->fetch();
  }

  // 批量导出
  public function export()
  {
    $data = $this->model->select();
    $csv = "商品名称,总库存,预警阈值\n";
    foreach ($data as $item) {
      $csv .= "{$item->name},{$item->total},{$item->threshold}\n";
    }

    return download($csv, 'stock_export_' . date('YmdHis') . '.csv');
  }

  // 表单模板
  protected function _form_filter(&$data)
  {
    if ($this->request->isPost()) {
      // 新增时初始化已用库存
      if (empty($data['id'])) {
        $data['used'] = 0;
      }
    }
  }
}
